package com.example.nacosconsumer.service;

import com.example.nacosconsumer.dao.ForumMapper;
import com.example.nacosconsumer.pojo.Remark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 递归查询评论树
 * author jusang
 */
@Service
public class GetRemark_Service {
    @Autowired
    ForumMapper forumService;

    @Bean
    public List<Remark> selectRemark(List<Integer> tiezi_ID) {
        //从数据库中取出所有评论
        List<Remark> All_List = forumService.selectRemark();
        return All_List.stream()
                //从所有评论中找出ParentID等于当前帖子ID的评论作为根评论
                .filter(Remark -> tiezi_ID.contains(Remark.getParentID()))
                //以根评论为依据进行递归调用getChildrens方法
                .map(Remark -> {
                    Remark.setChild_List(getChildrens(Remark, All_List));
                    return Remark;
                })
                //根据发布时间进行倒序排序
                .sorted(Comparator.comparing(Remark::getPublishTime).reversed())
                //转化为List类型
                .collect(Collectors.toList());
    }

    private List<Remark> getChildrens(Remark root, List<Remark> All_List) {
        return All_List.stream().filter(Remark -> {
            return Objects.equals(Remark.getParentID(), root.getID());
        }).map((Remark) -> {
            Remark.setChild_List(getChildrens(Remark, All_List));
            return Remark;
            //    按照日期对评论进行排序
        }).sorted(Comparator.comparing(Remark::getPublishTime).reversed()).collect(Collectors.toList());
    }

}
